/**
 * Created by sa on 2016/9/21.
 */

//phantomjs JQueryTest.js
"use strict";
var fs = require('fs')
var page = require('webpage').create();

var txtPath = 'D:/work_nodeJS/crawl_youku_nodejs/spider/JQueryTest.txt';
page.open('http://www.httpuseragent.org/', function (status) {

  console.log('Status: ' + status);

  if(status === "fail"){
    phantom.exit()
    return;
  }

  //page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
  page.includeJs("https://code.jquery.com/jquery-3.1.0.min.js", function () {
    console.log("includeJs")
    var a = page.evaluate(function () {
      //var href = $("#aswift_1").attr("width");

      //var href = $(document.getElementById('aswift_1').contentWindow.document.body).html()

      //var href = $("#aswift_1").contents().find("body").html();

      var adGoogle = $("#aswift_1").contents().find("iframe");
      var href = adGoogle.attr("src");


      //aswift_1 -> google_ads_frame2 adContent-clickOverlay
      //var href = $('#aswift_1').contents().find("iframe").contents().html();
      //.contents().find("body").html();
      //var href = adGoogle.contents().find("body").html() //.find("adContent-clickOverlay").attr("href");


      //var href = $('#google_ads_frame2').attr("id");

      return href;
    });
    console.log(a)


    try {
      fs.write(txtPath, "\n" + new Date() + "\n", 'a+');
      fs.write(txtPath, a, 'a+');
    } catch (e) {
      console.log(e);
    }
    console.log("tow top");

    page.open(a, function (status) {

      console.log("tow int");
      console.log('Status: ' + status);

      if(status === "fail"){
        phantom.exit()
        return;
      }

      page.includeJs("https://code.jquery.com/jquery-3.1.0.min.js", function () {
        console.log("第二个页面 includeJs")
        var bb = page.evaluate(function () {
          var adGoogle = $("#adContent-clickOverlay");
          var href = adGoogle.attr("href");
          return href;
        });
        console.log(bb)
        try {
          fs.write(txtPath, "\n" + new Date() + "\n", 'a+');
          fs.write(txtPath, bb, 'a+');
        } catch (e) {
          console.log(e);
        }
      });
    });
    //var savePath = 'D:/work_nodeJS/crawl_youku_nodejs/spider/' + new Date().valueOf() + '.png';
    //page.render(savePath);
    phantom.exit()
  });
});

